using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;

namespace JGSY.CMS.LowCode.Platform.Examples;

/// <summary>
/// 日志系统使用示例
/// 展示 Microsoft.Extensions.Logging + Serilog 混合架构的最佳实践
/// </summary>
public class LoggingUsageExamples
{
    private readonly ILogger<LoggingUsageExamples> _logger;
    private readonly LoggingPerformanceMonitor _performanceMonitor;
    private readonly IDataSanitizer _dataSanitizer;

    public LoggingUsageExamples(
        ILogger<LoggingUsageExamples> logger,
        LoggingPerformanceMonitor performanceMonitor,
        IDataSanitizer dataSanitizer)
    {
        _logger = logger;
        _performanceMonitor = performanceMonitor;
        _dataSanitizer = dataSanitizer;
    }

    /// <summary>
    /// 基础日志记录示例
    /// </summary>
    public async Task BasicLoggingExample()
    {
        // 1. 基础结构化日志
        _logger.LogInformation("用户 {UserId} 访问了页面 {PageName}", "user123", "Dashboard");

        // 2. 性能测量日志
        using var performance = _logger.MeasurePerformance("数据库查询操作");
        await SimulateAsyncOperation();
        // 性能日志会在 using 结束时自动记录

        // 3. 用户操作日志
        _logger.LogUserAction("user123", "创建文章", new { Title = "示例文章", Category = "技术" });

        // 4. 数据库操作日志
        _logger.LogDatabaseOperation("INSERT", "Articles", "article-456", elapsedMs: 125);

        // 5. API 调用日志
        _logger.LogApiCall("POST", "/api/articles", 201, 234, "user123");
    }

    /// <summary>
    /// 高性能日志记录示例
    /// </summary>
    public void HighPerformanceLoggingExample()
    {
        // 1. 条件日志记录（编译时优化）
        _logger.LogDebugHighPerformance("调试信息：处理项目 {ItemId}", "item-789");

        // 2. 批量日志记录
        var logEntries = new List<(string Message, object[] Args)>
        {
            ("处理项目 {ItemId}", new object[] { "item-1" }),
            ("处理项目 {ItemId}", new object[] { "item-2" }),
            ("处理项目 {ItemId}", new object[] { "item-3" })
        };
        _logger.LogBatch(LogLevel.Information, logEntries);

        // 3. 性能监控
        using var monitoring = _performanceMonitor.StartMonitoring();
        // 执行一些操作...
        Thread.Sleep(100);
        // 性能指标会在 using 结束时自动记录
    }

    /// <summary>
    /// 安全日志记录示例（敏感数据脱敏）
    /// </summary>
    public void SecureLoggingExample()
    {
        // 包含敏感信息的用户数据
        var userData = new Dictionary<string, object>
        {
            ["UserId"] = "user123",
            ["Password"] = "mySecretPassword",
            ["CreditCard"] = "1234-5678-9012-3456",
            ["Email"] = "user@example.com",
            ["PublicInfo"] = "这是公开信息"
        };

        // 安全的用户操作日志（自动脱敏）
        _logger.LogUserActionSafe(_dataSanitizer, "user123", "更新个人信息", userData);

        // 手动脱敏示例
        var sanitizedData = _dataSanitizer.SanitizeData(userData);
        _logger.LogInformation("已脱敏的用户数据：{@SanitizedData}", sanitizedData);
    }

    /// <summary>
    /// 错误处理和异常日志示例
    /// </summary>
    public async Task ErrorHandlingExample()
    {
        try
        {
            await RiskyOperation();
        }
        catch (Exception ex)
        {
            // 详细的异常日志
            _logger.LogError(ex, "操作失败：{OperationName}，参数：{@Parameters}", 
                "RiskyOperation", new { UserId = "user123", Timestamp = DateTime.UtcNow });

            // 结构化错误信息
            _logger.LogWarning("操作重试：尝试次数 {RetryCount}，下次重试时间 {NextRetryTime}", 
                3, DateTime.UtcNow.AddMinutes(5));
        }
    }

    /// <summary>
    /// 业务流程跟踪示例
    /// </summary>
    public async Task BusinessProcessTrackingExample()
    {
        var processId = Guid.NewGuid();
        var userId = "user123";

        // 流程开始
        _logger.LogInformation("业务流程开始：{ProcessId}，用户：{UserId}，流程：{ProcessName}", 
            processId, userId, "文章发布流程");

        try
        {
            // 步骤1：验证
            using var step1 = _logger.MeasurePerformance("文章内容验证");
            await ValidateContent();
            _logger.LogInformation("流程步骤完成：{ProcessId}，步骤：{StepName}，状态：{Status}", 
                processId, "内容验证", "成功");

            // 步骤2：保存
            using var step2 = _logger.MeasurePerformance("文章保存");
            await SaveContent();
            _logger.LogInformation("流程步骤完成：{ProcessId}，步骤：{StepName}，状态：{Status}", 
                processId, "内容保存", "成功");

            // 步骤3：发布
            using var step3 = _logger.MeasurePerformance("文章发布");
            await PublishContent();
            _logger.LogInformation("流程步骤完成：{ProcessId}，步骤：{StepName}，状态：{Status}", 
                processId, "内容发布", "成功");

            // 流程成功完成
            _logger.LogInformation("业务流程完成：{ProcessId}，状态：{Status}，总耗时：{TotalTime}", 
                processId, "成功", "未测量");
        }
        catch (Exception ex)
        {
            // 流程失败
            _logger.LogError(ex, "业务流程失败：{ProcessId}，失败步骤：{FailedStep}", 
                processId, "未知");
        }
    }

    /// <summary>
    /// 获取日志性能统计
    /// </summary>
    public void GetLoggingStatistics()
    {
        var (logCount, averageTimeMs) = _performanceMonitor.GetStatistics();
        _logger.LogInformation("日志性能统计：总日志数量 {LogCount}，平均耗时 {AverageTimeMs:F2}ms", 
            logCount, averageTimeMs);
    }

    // 模拟异步操作
    private static async Task SimulateAsyncOperation()
    {
        await Task.Delay(100);
    }

    // 模拟风险操作
    private static async Task RiskyOperation()
    {
        await Task.Delay(50);
        throw new InvalidOperationException("模拟的操作失败");
    }

    // 模拟验证内容
    private static async Task ValidateContent()
    {
        await Task.Delay(200);
    }

    // 模拟保存内容
    private static async Task SaveContent()
    {
        await Task.Delay(300);
    }

    // 模拟发布内容
    private static async Task PublishContent()
    {
        await Task.Delay(150);
    }
}

/// <summary>
/// 控制器中的日志使用示例
/// </summary>
public class ExampleController
{
    private readonly ILogger<ExampleController> _logger;
    private readonly IDataSanitizer _dataSanitizer;

    public ExampleController(ILogger<ExampleController> logger, IDataSanitizer dataSanitizer)
    {
        _logger = logger;
        _dataSanitizer = dataSanitizer;
    }

    /// <summary>
    /// API 端点日志示例
    /// </summary>
    public async Task<IActionResult> CreateArticle([FromBody] CreateArticleRequest request)
    {
        var requestId = Guid.NewGuid();
        
        // 记录API调用开始
        _logger.LogInformation("API调用开始：{RequestId}，端点：{Endpoint}，用户：{UserId}", 
            requestId, "POST /api/articles", request.UserId);

        using var performance = _logger.MeasurePerformance($"创建文章-{requestId}");

        try
        {
            // 记录输入参数（脱敏）
            var sanitizedRequest = _dataSanitizer.SanitizeData(request);
            _logger.LogDebug("请求参数：{RequestId}，参数：{@Parameters}", requestId, sanitizedRequest);

            // 业务逻辑...
            var result = await ProcessCreateArticle(request);

            // 记录成功结果
            _logger.LogInformation("API调用成功：{RequestId}，结果ID：{ResultId}", 
                requestId, result.Id);

            return new OkResult(); // 返回实际结果
        }
        catch (Exception ex)
        {
            // 记录错误
            _logger.LogError(ex, "API调用失败：{RequestId}，错误：{ErrorMessage}", 
                requestId, ex.Message);
            
            return new BadRequestResult(); // 返回错误结果
        }
    }

    private static async Task<CreateArticleResult> ProcessCreateArticle(CreateArticleRequest request)
    {
        await Task.Delay(500); // 模拟处理
        return new CreateArticleResult { Id = Guid.NewGuid() };
    }
}

// 示例数据传输对象
public class CreateArticleRequest
{
    public string UserId { get; set; } = string.Empty;
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty; // 敏感信息
}

public class CreateArticleResult
{
    public Guid Id { get; set; }
}

// 模拟的返回类型
public interface IActionResult { }
public class OkResult : IActionResult { }
public class BadRequestResult : IActionResult { }
public class FromBodyAttribute : Attribute { }
